<template>
  <view class="container">
    <view class="apply-main">
      <view v-if="lastApply && !isEdit" class="audit-result">
        <view v-if="lastApply.status === 0">
          <image class="icon" src="/static/commission/ic_audit.png"></image>
          <view class="message">申请已提交，正在审核中</view>
          <view class="time">{{ lastApply.create_time }} 提交</view>
          <view v-if="setting.join_type === 'pay' && setting.price > 0" class="btn-pay" @tap="doPay()">支付{{ setting.price }}元，立即通过审核</view>
        </view>
        <view v-if="lastApply.status === 1">
          <image class="icon" src="/static/commission/ic_pass.png"></image>
          <view class="message">恭喜你，已通过审核</view>
          <view class="time">{{ lastApply.create_time }} 提交</view>
          <view class="btn" @tap="toCommission">进入推广中心</view>
        </view>
        <view v-if="lastApply.status === 2">
          <image class="icon" src="/static/commission/ic_reject.png"></image>
          <view class="message">审核被驳回，可调整后重新提交</view>
          <view class="time">{{ lastApply.create_time }} 提交</view>
          <view class="btn" @tap="toEdit">返回编辑</view>
          <view class="reject">驳回原因：{{ lastApply.reject_reason ? lastApply.reject_reason : '无' }}</view>
        </view>
      </view>
      <view v-else class="apply-form">
        <view class="form-item">
          <text class="label">姓名</text>
          <input type="text" class="input" placeholder="请输入姓名" v-model="name"/>
        </view>
        <view class="form-item">
          <text class="label">手机</text>
          <input type="text" class="input" maxlength="11" placeholder="请输入手机号" v-model="phone"/>
        </view>
        <view class="form-item" style="display: flex; align-items: center; padding-top: 30rpx">
          <label class="agreement">
            <checkbox-group @change="checkboxChange">
              <checkbox class="check" :value="true" :checked="is_agree" color="#ea4679"/>
              阅读并同意
            </checkbox-group>
          </label>
          <text class="agreement" @tap="toAgreement" style="color: #ea4679">《用户推广协议》</text>
        </view>
        <view class="form-item">
          <button v-if="setting.join_type === 'apply' || setting.price <= 0" class="btn-apply" @tap="doSubmit">立即申请</button>
          <button v-if="setting.join_type === 'pay'" class="btn-apply" @tap="doSubmit">支付{{ setting.price }}元，立即加入</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      name: '',
      phone: '',
      is_agree: false,
      pid: 0,
      focus: '',
      lastApply: null,
      isEdit: false,
      setting: {},
      openid: ''
    }
  },
  onLoad(options) {
    if (options.pid) {
      this.pid = options.pid
    }
    this.getLastApply();
  },
  onShow() {
    this.getSetting()
  },
  onPullDownRefresh() {
    this.getSetting()
    this.getLastApply();
    setTimeout(() => {
      uni.hideNavigationBarLoading(); //完成停止加载
      uni.stopPullDownRefresh(); //停止下拉刷新
    }, 500);
  },
  methods: {
    doSubmit: function () {
      const that = this;
      let name = this.name;
      let phone = this.phone;
      let pid = this.pid;
      let is_agree = this.is_agree;
      if (!name) {
        this.$util.message('请输入姓名', 'error');
        return;
      }
      if (!phone) {
        this.$util.message('请输入手机号', 'error');
        return;
      }
      if (!is_agree) {
        this.$util.message('请阅读并同意《用户推广协议》', 'error');
        this.is_agree = true
        return;
      }
      var platform = 'wxapp'
      // #ifdef WEB
      platform = 'h5'
      // #endif
      this.$util.request({
        url: '/commission/apply',
        data: {
          name: name,
          phone: phone,
          pid: pid,
          platform: platform
        }
      }).then((res) => {
        if (this.setting.join_type === 'pay') {
          this.doPay()
        } else {
          uni.showModal({
            title: '提示',
            content: res.message,
            showCancel: false,
            confirmText: '确定',
            success() {
              that.lastApply = null
              that.isEdit = false
              that.getLastApply();
            }
          });
        }
      });
    },
    doPay() {
      this.paying = true
      setTimeout(() => {
        this.paying = false
      }, 2000);

      var platform = 'wxapp'
      // #ifdef WEB
      platform = 'h5'
      // #endif
      this.$util.request({
        url: '/pay/createOrder',
        data: {
          platform: platform,
          trade_type: 'jsapi',
          type: 'commission',
          package_id: 0,
          openid: this.openid
        }
      }).then((res) => {
        var that = this
        var paySuccess = function () {
          that.$util.message('支付成功', 'error', function () {
            that.getLastApply();
          });
        };
        var payFail = function (res) {
          if (res.errMsg.indexOf('cancel') === -1) {
            that.getLastApply();
            that.$util.message('发起支付失败：' + res.errMsg);
          }
        };

        var trade_type = res.data.trade_type;
        if (trade_type === 'jsapi') {
          const jssdk = res.data.jssdk;
          const orderInfo = res.data.orderInfo;
          uni.requestPayment({
            provider: 'wxpay',
            orderInfo: {
              appid: orderInfo.appid,
              mch_id: orderInfo.mch_id,
              nonce_str: orderInfo.nonce_str,
              prepay_id: orderInfo.prepay_id,
              sign: orderInfo.sign
            },
            timeStamp: jssdk.timestamp,
            nonceStr: jssdk.nonceStr,
            package: jssdk.package,
            signType: jssdk.signType,
            paySign: jssdk.paySign,
            success: paySuccess,
            fail: payFail
          })
        } else if (trade_type === 'native') {
          uni.redirectTo({
            url: '/pages/pay/qrcode?total_fee=' + res.data.total_fee + '&order_id=' + res.data.order_id + '&pay_url=' + encodeURIComponent(res.data.pay_url)
          })
        } else if (trade_type === 'h5') {
          setTimeout(() => {
            uni.showModal({
              title: '提示',
              content: '已完成支付？',
              cancelText: '支付失败',
              confirmText: '我已支付',
              complete: function (res) {
                that.getLastApply()
              }
            })
          }, 1000)
          window.location.href = res.data.pay_url
        }
      })
    },
    getWxappOpenid() {
      const that = this
      wx.login({
        success: function (e) {
          var code = e.code
          that.$util.request({
            url: '/wxapp/getOpenid',
            data: {
              code: code
            }
          }).then(res => {
            that.openid = res.data.openid;
          })
        },
        fail: function (e) {
          console.log(e);
        }
      });
    },

    toAgreement() {
      uni.navigateTo({
        url: '/pages/article/detail?type=commission_agree'
      });
    },

    toCommission() {
      uni.redirectTo({
        url: '/pages/commission/index'
      });
    },

    toEdit() {
      this.isEdit = true
    },

    getLastApply() {
      this.$util.request({
        url: '/commission/getLastApply'
      }).then((res) => {
        if (res.data) {
          this.lastApply = res.data
          this.name = res.data.name
          this.phone = res.data.phone
        }
      });
    },

    getSetting() {
      this.$util.request({
        url: '/commission/getSetting'
      }).then((res) => {
        this.setting = res.data
        if (!this.setting.is_open) {
          this.$util.message('推广功能已关闭，如有疑问请联系平台客服', 'error', function () {
            uni.switchTab({
              url: '/pages/my/my'
            })
          })
        } else {
          // #ifdef MP-WEIXIN
          if (this.setting.join_type === 'pay' && this.setting.price > 0) {
            this.getWxappOpenid()
          }
          // #endif
        }
      })
    },

    checkboxChange(e) {
      let value = e.detail.value;
      this.is_agree = value.length > 0
    }
  }
};
</script>
<style>
.container {
  position: relative;
  padding: 0;
}

.apply-main {
  padding: 80rpx 80rpx;
  background: rgba(255, 255, 255, 0.8);
  margin: 60rpx 30rpx 0 30rpx;
  border-radius: 20rpx;
}

.apply-main .audit-result {
  text-align: center;
  margin-top: 88rpx;
}

.apply-main .audit-result .icon {
  width: 120rpx;
  height: 120rpx;
}

.apply-main .audit-result .message {
  width: 100%;
  line-height: 44rpx;
  font-size: 36rpx;
  color: #666;
  margin-top: 60rpx;
}

.apply-main .audit-result .time {
  width: 100%;
  line-height: 44rpx;
  font-size: 24rpx;
  color: #999;
  margin-top: 20rpx;
}

.apply-main .audit-result .btn {
  width: 240rpx;
  height: 60rpx;
  border: 1px solid #666;
  border-radius: 10rpx;
  line-height: 60rpx;
  text-align: center;
  margin: 0 auto;
  margin-top: 60rpx;
  font-size: 28rpx;
  color: #666;
}

.apply-main .audit-result .btn-pay {
  color: #ea4679;
  border: 1px solid #ea4679;
  border-radius: 44rpx;
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 30rpx;
  margin: 100rpx auto 0 auto;
}

.apply-main .audit-result .reject {
  font-size: 28rpx;
  color: red;
  margin-top: 40rpx;
  line-height: 44rpx;
}

.apply-main .apply-form .form-item {
  display: flex;
  align-items: center;
  position: relative;
  margin-bottom: 40rpx;
}

.apply-main .apply-form .form-item .input {
  width: 100%;
  border: none;
  border-bottom: 2px solid #ea4679;
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 20rpx 0 180rpx;
}

.apply-main .apply-form .form-item .label {
  font-size: 32rpx;
  line-height: 40rpx;
  position: absolute;
  left: 20rpx;
  top: 20rpx;
}

.apply-main .apply-form .form-item .icon {
  width: 36rpx;
  height: 36rpx;
  position: absolute;
  left: 20rpx;
  top: 20rpx;
}

.apply-main .apply-form .form-item .check {
  transform: scale(0.75);
  margin-right: 6rpx;
}

.apply-main .apply-form .form-item .agreement {
  font-size: 28rpx;
  color: #666;
  display: flex;
  align-items: center;
}

.apply-main .apply-form .form-item .agreement text {
  color: #000;
}

.apply-main .apply-form .form-item .btn-apply {
  color: #fff;
  background: #ea4679;
  border-radius: 44rpx;
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  margin: 100rpx auto 0 auto;
}
</style>
